<?php
namespace Common\Service;

require_once dirname(__FILE__) . '/../../../../vendor/tencent/tls-sig-api-v2/src/TLSSigAPIv2.php';


use Tencent\TLSSigAPIv2;

class TencentIM
{
    public function TencentIM()
    {
        $TLS_APPID = getenv('TLS_IM_APPID');
        $TLS_KEY = getenv('TLS_IM_KEY');
        $sdkappid = $TLS_APPID; // 替换为你的SDKAppID
        $identifier = 'nalan'; // 替换为你的Identifier（管理员账号）
        $api = new TLSSigAPIv2($TLS_APPID, $TLS_KEY);// 替换为你的UserSig
        $usersig = $api->genSig($identifier);

        return compact('sdkappid', 'identifier', 'usersig');
    }

    public function uniImPost($url, $data)
    {
        $tim = $this->TencentIM();

        $sdkappid = $tim['sdkappid']; // 替换为你的SDKAppID
        $identifier = $tim['identifier']; // 替换为你的Identifier（管理员账号）
        $usersig = $tim['usersig'];

        $random = rand(10000000, 99999999);

        $url = "https://console.tim.qq.com/$url?sdkappid=$sdkappid&identifier=$identifier&usersig=$usersig&random=$random&contenttype=json";
        // var_dump($data);exit;

        return http_post($url, $data);
    }

    // 发送消息
    public function sendmsg($from, $to, $msgContent, $custom_data = '', $single = 0) {
        $url = "v4/openim/sendmsg";

        if ($custom_data && is_array($custom_data)) {
            $custom_data = json_encode($custom_data, JSON_UNESCAPED_UNICODE);
        }
        
        $random = rand(10000000, 99999999);
        
        // 请求体
        $data = [
            // "SyncOtherMachine" => $single ? 2 : 1,
             "SyncOtherMachine" =>1,
            "From_Account" => (string)$from,
            "To_Account" => (string)$to,
            "OnlineOnlyFlag" => 0,
            "MsgSeq" => 93847636,
            "MsgRandom" => $random,
            "MsgBody" => [
                [
                    "MsgType" => "TIMTextElem",
                    "MsgContent" => [
                        "Text" => $msgContent
                    ]
                ]
            ],
            "CloudCustomData" => $custom_data
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 批量发单聊消息
    public function batchsendmsg($from, $to, $msgContent) {
        $url = "v4/openim/batchsendmsg";
        
        $random = rand(10000000, 99999999);
        
        // 请求体
        $data = [
            "SyncOtherMachine" => 1,
            "From_Account" => (string)$from,
            "To_Account" => (string)$to,
            "OnlineOnlyFlag" => 0,
            "MsgSeq" => 28360,
            "MsgRandom" => $random,
            "MsgBody" => [
                [
                    "MsgType" => "TIMTextElem",
                    "MsgContent" => [
                        "Text" => $msgContent
                    ]
                ]
            ],
            "CloudCustomData" => "自定义数据",
            "OfflinePushInfo"=> [
                "PushFlag"=> 0,
                "Desc"=> "离线推送内容",
                "Ext"=> "这是透传的内容",
                "AndroidInfo"=> [
                    "Sound"=> "shake" //Android 系统通知铃声文件名，详情见“消息格式描述”。
                ],
                "ApnsInfo"=> [
                    "Sound"=> "apns.mp3", // iOS 系统通知铃声文件名，详情见“消息格式描述”。
                    "BadgeMode"=> 1, // 这个字段缺省或者为 0 表示需要计数，为 1 表示本条消息不需要计数，即右上角图标数字不增加
                    "Title"=>"apns title", // apns title
                    "SubTitle"=>"apns subtitle", // apns subtitle
                    "Image"=>"www.image.com" // image url
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 创建用户
    // 导入单个账号
    public function account_import($UserID, $Nick, $FaceUrl) {
        $url = "v4/im_open_login_svc/account_import";
        
        // 请求体
        $data = [
            "UserID" => (string)$UserID,
            "Nick" => $Nick,
            "FaceUrl" => $FaceUrl,
        ];

        $response = $this->uniImPost($url, $data);
        // halt($response);
        return $response;
    }

    // 用户资料
    public function account_check($UserID)
    {
        $url = "v4/im_open_login_svc/account_check";

        // 请求体
        $data = [
            "CheckItem"=>[
                [
                    "UserID"=>(string)$UserID
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 用户资料
    public function portrait_get($UserID)
    {
        $url = "v4/profile/portrait_get";

        // 请求体
        $data = [
            "To_Account"=>[(string)$UserID],
            "TagList"=>[
                "Tag_Profile_IM_Nick",
                "Tag_Profile_IM_Image",
                "Tag_Profile_IM_Gender",
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 批量获取用户资料
    public function portrait_gets($UserIDs)
    {
        $url = "v4/profile/portrait_get";

        // 请求体
        $data = [
            "To_Account"=>$UserIDs,
            "TagList"=>[
                "Tag_Profile_IM_Nick",
                "Tag_Profile_IM_Image",
                "Tag_Profile_IM_Gender",
            ]
        ];

        $response = $this->uniImPost($url, $data);

        $userinfos = [];
        foreach ($response['UserProfileItem'] as $key => $value) {
            foreach ($value['ProfileItem'] as $k => $v) {
                $userinfo[$v['Tag']] = $v['Value'];
            }
            $userinfos[$value['To_Account']] = $userinfo;
        }

        return $userinfos;
    }

    // 拉取会话列表
    public function get_list($UserID)
    {
        $url = "v4/recentcontact/get_list";

        $data = [
            "From_Account"=> (string)$UserID,
            "TimeStamp"=> 0,
            "StartIndex"=> 0,
            "TopTimeStamp"=> 0,
            "TopStartIndex"=> 0,
            "AssistFlags"=> 7
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 历史消息
    // 拉取单聊历史消息
    public function admin_getroammsg($UserID, $UserID2, $MaxCnt = 20, $MaxTime = 0, $MsgKey = '')
    {
        $url = "v4/openim/admin_getroammsg";

        $timenow = time();

        $data = [
            "Operator_Account"=>(string)$UserID,
            "Peer_Account"=>(string)$UserID2,
            "MaxCnt"=>$MaxCnt,
            "MinTime"=>$timenow - 7 * 60 * 60 * 24,
            "MaxTime"=>$MaxTime?:$timenow
        ];
        if ($MsgKey) {
            $data['LastMsgKey'] = $MsgKey;
        }

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 查询未读单聊消息数
    // public function get_c2c_unread_msg_num($UserID, $touids)
    // {
    //     $url = "v4/openim/get_c2c_unread_msg_num";

    //     $data = [
    //         "To_Account"=>(string)$UserID,
    //         "Peer_Account"=>$touids
    //     ];

    //     $response = $this->uniImPost($url, $data);
    //     $unreads = [];
    //     foreach ($response['C2CUnreadMsgNumList'] as $key => $value) {
    //         $unreads[$value['Peer_Account']] = $value['C2CUnreadMsgNum'];
    //     }

    //     return $unreads;
    // }
    
    
        public function get_c2c_unread_msg_num($UserID, $touids)
    {
        $url = "v4/openim/get_c2c_unread_msg_num";
        $chunkSize = 90; // 每个小数组的大小
        $chunks = array_chunk($touids, $chunkSize);
        $newResult = [];
        foreach ($chunks as $key=>$chunk){
            $data = [
                "To_Account"=>(string)$UserID,
                "Peer_Account"=>$chunk
            ];
            $response = $this->uniImPost($url, $data);
            if (isset($response['ErrorCode'])  && $response['ErrorCode']==0){
                $newResult = array_merge($newResult,$response['C2CUnreadMsgNumList']);
            }
        }
        $unreads = [];
        foreach ($newResult as $key => $value) {
            $unreads[$value['Peer_Account']] = $value['C2CUnreadMsgNum'];
        }
        return $unreads;
    }
    
    
    
    
    

    // 1 表示置顶会话 2 表示取消置顶
    // 会话置顶
    public function top($from, $to, $type = 1)
    {
        $url = "v4/recentcontact/top";

        $data = [
            "From_Account"=>(string)$from,
            "OperationType"=>$type,
            "RecentContactItem"=> [
                [
                    "Type"=> 1,
                    "To_Account"=> (string)$to
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 撤回单聊消息
    public function admin_msgwithdraw($from, $to, $MsgKey)
    {
        $url = "v4/openim/admin_msgwithdraw";

        $data = [
            "From_Account"=>(string)$from,
            "To_Account"=>(string)$to,
            "MsgKey"=>$MsgKey,
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 单向删除单聊历史消息
    // 指定以 from 的身份将会话 to 中的单聊消息删除。
    public function delete_c2c_msg_ramble($from, $to, $MsgKeyList)
    {
        $url = "v4/openim/delete_c2c_msg_ramble";

        $data = [
            "Operator_Account"=>(string)$from,
            "Peer_Account"=>(string)$to,
            "MsgKeyList"=>$MsgKeyList,
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 发送单聊消息已读回执
    // 指定以 from 的身份将会话 to 中的单聊消息设置为已读。
    public function c2c_msg_read_receipt($from, $to, $MsgKey)
    {
        $url = "v4/openim/c2c_msg_read_receipt";

        $data = [
            "Operator_Account"=>(string)$from,
            "Peer_Account"=>(string)$to,
            "C2CMsgInfo"=>[
                [
                    "From_Account"=>(string)$to,
                    "To_Account"=>(string)$from,
                    "MsgKey"=>$MsgKey,
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }
    
    
    public function c2c_msg_read_receipt_unread($from, $to,$user_unread_list=[])
    {
        $url = "v4/openim/c2c_msg_read_receipt";
        $data = [
            "Operator_Account"=>(string)$from,
            "Peer_Account"=>(string)$to,
            "C2CMsgInfo"=>$user_unread_list
        ];
        $response = $this->uniImPost($url, $data);
        return $response;
    }


    // 删除单个会话
    // 指定以 from 的身份将会话 to 中的会话删除
    public function recentcontact_delete($from, $to)
    {
        $url = "v4/recentcontact/delete";

        $data = [
            "From_Account"=>(string)$from,
            "Type"=>1,
            "To_Account"=>(string)$to,
            "ClearRamble"=>1,
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 清理单聊会话的未读消息计数
    // 管理员指定 from 将会话 to 的单聊未读计数清除。
    public function admin_set_msg_read($from, $to)
    {
        $url = "v4/openim/admin_set_msg_read";

        $data = [
            "Report_Account"=>(string)$from,
            "Peer_Account"=>(string)$to,
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 修改单聊历史消息
    // 管可以单独修改消息中的 MsgBody 或 CloudCustomData 字段，也可以同时修改这两个字段。以请求中指定的字段值覆盖历史消息对应的字段。
    public function modify_c2c_msg($from, $to, $MsgKey, $CloudCustomData)
    {
        $url = "v4/openim/modify_c2c_msg";

        $data = [
            "From_Account"=>(string)$from,
            "To_Account"=>(string)$to,
            "MsgKey"=>$MsgKey,
            "CloudCustomData"=>$CloudCustomData,
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 删除账号
    public function account_delete($from)
    {
        $url = "v4/im_open_login_svc/account_delete";

        $data = [
            "DeleteItem"=>[
                [
                    "UserID"=>(string)$from
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 创建用户
    // 导入多个账号
    public function multiaccount_import($AccountList) {
        $url = "v4/im_open_login_svc/multiaccount_import";
        
        // 请求体
        $data = [
            "AccountList" => $AccountList
        ];

        $response = $this->uniImPost($url, $data);
        // halt($response);
        return $response;
    }

    // 创建或更新会话标记数据
    public function mark_contact($from, $to, $GroupName)
    {
        $url = "v4/recentcontact/mark_contact";

        $data = [
            "From_Account"=>(string)$from,
            "MarkItem"=>[
                [
                    "OptType"=>3,
                    "ContactItem"=>[
                        "Type"=>1,                   
                        "To_Account"=>(string)$to
                    ],
                    "SetMark"=>[1,2,3],
                    "CustomMark"=>$GroupName
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 创建会话分组数据
    public function create_contact_group($from, $to, $GroupName)
    {
        $url = "v4/recentcontact/create_contact_group";

        $data = [
            "From_Account"=>(string)$from,
            "GroupContactItem"=>[
                [
                    "GroupName"=>$GroupName,
                    "ContactItem"=> [
                        [
                            "Type"=> 1,
                            "To_Account"=> (string)$to
                        ]
                    ]
                ]
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

    // 单发推送
    public function batch($from, $to, $PushFlag = 0, $Title, $Desc = '')
    {
        $url = "v4/timpush/batch";
        $random = rand(1000000, 9999999);

        $data = [
            "From_Account"=>(string)$from,
            "To_Account"=>[(string)$to],
            "MsgRandom"=>$random,
            "OfflinePushInfo"=>[
                "PushFlag"=>$PushFlag,
                "Title"=>$Title,
                "Desc"=>$Desc,
            ]
        ];

        $response = $this->uniImPost($url, $data);

        return $response;
    }

}